/// Copyright (c) 2018 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology.  Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.

import UIKit
import KooberUIKit
import RxSwift
import RxCocoa
import KooberKit
import SnapKit

class SignInRootView: NiblessView {

  // MARK: - Properties
  let viewModel: SignInViewModel
  let disposeBag = DisposeBag()
  var hierarchyNotReady = true
  var bottomLayoutConstraint: NSLayoutConstraint?

  let scrollView: UIScrollView = UIScrollView()
  let contentView: UIView = UIView()
  
    let tipView: UIView = {
        var view = UIView()
        
        let imageView = UIImageView()
        imageView.image = UIImage(named: "loginIcon")
        view.addSubview(imageView)

        imageView.snp.makeConstraints { (make) -> Void in
            make.width.height.equalTo(32)
            make.left.equalTo(0)
            make.top.equalTo(0)
        }
        
        let title = UILabel()
        title.text = "用户名/手机号登录"
        title.textColor = Color.loginTitleColor
        title.font = UIFont.init(name: "PingFangSC-Semibold", size: 20)
        view.addSubview(title)
        
        title.snp.makeConstraints({ (make) in
            make.width.equalTo(280)
            make.height.equalTo(28)
            make.left.equalTo(imageView.snp.right).offset(14)
            make.centerY.equalTo(imageView)
        })
        return view
    }()
    
//  lazy var inputStack: UIStackView = {
//    let stack = UIStackView(arrangedSubviews: [
//      userNameField,
//      //userNameBottomLine,
//      passwordField
//    ])
//    stack.axis = .vertical
//    stack.spacing = 10
//    return stack
//  }()

//  lazy var userNameInputStack: UIStackView = {
//    let stack = UIStackView(arrangedSubviews: [userNameField, userNameBottomLine])
//    stack.axis = .vertical
//    return stack
//  }()


    
//  let emailIcon: UIView = {
//    let imageView = UIImageView()
//    imageView.heightAnchor
//      .constraint(equalToConstant: 40)
//      .isActive = true
//    imageView.widthAnchor
//      .constraint(equalToConstant: 40)
//      .isActive = true
//    imageView.image = #imageLiteral(resourceName: "email_icon")
//    imageView.contentMode = .center
//    return imageView
//  }()

  let userNameField: UITextField = {
    let field = UITextField()
    field.placeholder = "用户名/手机号"
    field.font = UIFont.systemFont(ofSize: 16)
    //field.backgroundColor = Color.loginTextTintColor
    field.textColor = Color.loginTextTintColor
    //field.keyboardType = .emailAddress
    field.autocapitalizationType = .none
    field.autocorrectionType = .no
    return field
  }()
    
  let userNameBottomLine: UIView = {
        let lineView = UIView()
        lineView.heightAnchor.constraint(equalToConstant: 1)
        lineView.backgroundColor = Color.loginBottomLineColor
        return lineView
    }()

//  lazy var passwordInputStack: UIStackView = {
//    let stack = UIStackView(arrangedSubviews: [passwordIcon, passwordField])
//    stack.axis = .horizontal
//    return stack
//  }()

//  let passwordIcon: UIView = {
//    let imageView = UIImageView()
//    imageView.heightAnchor
//      .constraint(equalToConstant: 40)
//      .isActive = true
//    imageView.widthAnchor
//      .constraint(equalToConstant: 40)
//      .isActive = true
//    imageView.image = #imageLiteral(resourceName: "password_icon")
//    imageView.contentMode = .center
//    return imageView
//  }()

  let passwordField: UITextField = {
    let field = UITextField()
    field.font = UIFont.systemFont(ofSize: 16)
    field.placeholder = "请输入密码"
    field.isSecureTextEntry = true
    field.textColor = Color.loginTextTintColor
    //field.backgroundColor = Color.background
    return field
  }()
    let forgetPasswordButton:UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("忘记密码", for: .normal)
        //button.setTitle("", for: .disabled)
        button.titleLabel?.font = .systemFont(ofSize: 14)
        button.setTitleColor(Color.loginTextTintColor, for: .normal)
        return button
    }()
    
    let verticalLine:UIView = {
        let lineView = UIView()
        lineView.backgroundColor = Color.loginBottomLineColor
        return lineView
    }()
    
    let lookUpPasswordButton:UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("", for: .normal)
        button.setImage(UIImage.init(named: "lookUpPassword"), for: .normal)
        return button
    }()

  let passwordBottomLine: UIView = {
        let lineView = UIView()
        lineView.heightAnchor.constraint(equalToConstant: 1)
        lineView.backgroundColor = Color.loginBottomLineColor
        return lineView
    }()
    
  let signInButton: UIButton = {
    let button = UIButton(type: .custom)
    button.setTitle("登录", for: .normal)
    button.setTitle("", for: .disabled)
    button.titleLabel?.font = .boldSystemFont(ofSize: 17)
    button.layer.cornerRadius = 10
    button.backgroundColor = Color.loginButtonEnableColor
    return button
  }()

  let signInActivityIndicator: UIActivityIndicatorView  = {
    let indicator = UIActivityIndicatorView(style: .white)
    indicator.hidesWhenStopped = true
    return indicator
  }()
    
    let loginStyleExchangeButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("短信验证码登录", for: .normal)
        //button.setTitle("", for: .disabled)
        button.titleLabel?.font = .boldSystemFont(ofSize: 14)
        button.setTitleColor(Color.loginExchangeButtonColor, for: .normal)
        return button
    }()

  // MARK: - Methods
  init(frame: CGRect = .zero,
       viewModel: SignInViewModel) {
    self.viewModel = viewModel
    super.init(frame: frame)
    bindTextFieldsToViewModel()
    bindViewModelToViews()
  }

  func bindTextFieldsToViewModel() {
    bindEmailField()
    bindPasswordField()
  }

  func bindEmailField() {
    userNameField.rx.text
      .asDriver()
      .map { $0 ?? "" }
      .drive(viewModel.emailInput)
      .disposed(by: disposeBag)
  }

  func bindPasswordField() {
    passwordField.rx.text
      .asDriver()
      .map { $0 ?? "" }
      .drive(viewModel.passwordInput)
      .disposed(by: disposeBag)
  }

  override func didMoveToWindow() {
    super.didMoveToWindow()
    guard hierarchyNotReady else {
      return
    }
    backgroundColor = Color.loginBG
    constructHierarchy()
    activateConstraints()
    wireController()
    hierarchyNotReady = false
  }

  func constructHierarchy() {
    scrollView.addSubview(contentView)
    contentView.addSubview(tipView)
    contentView.addSubview(userNameField)
    contentView.addSubview(userNameBottomLine)
    contentView.addSubview(passwordField)
    contentView.addSubview(forgetPasswordButton)
    contentView.addSubview(verticalLine)
    contentView.addSubview(lookUpPasswordButton)
    contentView.addSubview(passwordBottomLine)
    contentView.addSubview(signInButton)
    signInButton.addSubview(signInActivityIndicator)
    contentView.addSubview(loginStyleExchangeButton)
    addSubview(scrollView)
  }

  func activateConstraints() {
    activateConstraintsScrollView()
    activateConstraintsContentView()
    activateConstraintsInputStack()
    activateConstraintsSignInButton()
    activateConstraintsSignInActivityIndicator()
  }

  func wireController() {
    signInButton.addTarget(viewModel,
                           action: #selector(SignInViewModel.signIn),
                           for: .touchUpInside)
  }
  
  func configureViewAfterLayout() {
    //resetScrollViewContentInset()
  }
  
//  func resetScrollViewContentInset() {
//    let scrollViewBounds = scrollView.bounds
//    let contentViewHeight = CGFloat(180.0)
//
//    var scrollViewInsets = UIEdgeInsets.zero
//    scrollViewInsets.top = scrollViewBounds.size.height / 2.0;
//    scrollViewInsets.top -= contentViewHeight / 2.0;
//
//    scrollViewInsets.bottom = scrollViewBounds.size.height / 2.0
//    scrollViewInsets.bottom -= contentViewHeight / 2.0
//
//    scrollView.contentInset = scrollViewInsets
//  }
  
  func moveContentForDismissedKeyboard() {
    //resetScrollViewContentInset()
  }
  
  func moveContent(forKeyboardFrame keyboardFrame: CGRect) {
    var insets = scrollView.contentInset
    insets.bottom = keyboardFrame.height
    scrollView.contentInset = insets
  }
}

// MARK: - Layout
extension SignInRootView {
  
  func activateConstraintsScrollView() {
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    scrollView.snp.makeConstraints { (make) in
        make.top.equalTo(safeAreaLayoutGuide)
        make.bottom.equalTo(safeAreaLayoutGuide)
        make.left.equalTo(safeAreaLayoutGuide)
        make.right.equalTo(safeAreaLayoutGuide)
    }
    
//    let leading = scrollView.leadingAnchor
//      .constraint(equalTo: layoutMarginsGuide.leadingAnchor)
//    let trailing = scrollView.trailingAnchor
//      .constraint(equalTo: layoutMarginsGuide.trailingAnchor)
//    let top = scrollView.topAnchor
//      .constraint(equalTo: safeAreaLayoutGuide.topAnchor)
//    let bottom = scrollView.bottomAnchor
//      .constraint(equalTo: safeAreaLayoutGuide.bottomAnchor)
//    NSLayoutConstraint.activate(
//      [leading, trailing, top, bottom])
  }

  func activateConstraintsContentView() {
    //contentView.translatesAutoresizingMaskIntoConstraints = false
    contentView.snp.updateConstraints { (make) in
        //make.width.equalTo(scrollView)
        //make.height.equalTo(651)
        make.leading.equalTo(scrollView)
        make.trailing.equalTo(scrollView)
        make.top.equalTo(scrollView)
        make.bottom.equalTo(scrollView)
    }
//    let width = contentView.widthAnchor
//      .constraint(equalTo: scrollView.widthAnchor)
//    let leading = contentView.leadingAnchor
//      .constraint(equalTo: scrollView.leadingAnchor)
//    let trailing = contentView.trailingAnchor
//      .constraint(equalTo: scrollView.trailingAnchor)
//    let top = contentView.topAnchor
//      .constraint(equalTo: scrollView.topAnchor)
//    let bottom = contentView.bottomAnchor
//      .constraint(equalTo: scrollView.bottomAnchor)
//    NSLayoutConstraint.activate(
//      [width, leading, trailing, top, bottom])
  }

  func activateConstraintsInputStack() {
    
    tipView.snp.makeConstraints { (make) in
        make.top.equalTo(31)
        make.height.equalTo(32)
        make.width.equalTo(335)
        make.centerX.equalTo(Size.SCREEN_WIDTH/2)

    }
    userNameField.snp.makeConstraints { (make) in
        make.top.equalTo(tipView.snp.bottom).offset(52)
        make.width.equalTo(335)
        make.height.equalTo(22)
        //make.left.equalTo(20)
        make.centerX.equalTo(tipView)
    }
    
    userNameBottomLine.snp.makeConstraints { (make) in
        make.top.equalTo(userNameField.snp.bottom).offset(12)
        make.width.equalTo(335)
        make.height.equalTo(1)
        make.centerX.equalTo(userNameField.snp.centerX)
    }
    passwordField.snp.makeConstraints { (make) in
        make.top.equalTo(userNameBottomLine.snp.bottom).offset(27)
        make.width.equalTo(250)
        make.height.equalTo(22)
        make.left.equalTo(userNameField)
    }
    
    forgetPasswordButton.snp.makeConstraints { (make) in
        make.right.equalTo(userNameBottomLine)
        make.width.equalTo(60)
        make.height.equalTo(20)
        make.centerY.equalTo(passwordField)
    }
    
    verticalLine.snp.makeConstraints { (make) in
        make.right.equalTo(forgetPasswordButton.snp.left).offset(-4)
        make.width.equalTo(1)
        make.height.equalTo(15)
        make.centerY.equalTo(passwordField)
    }
    
    lookUpPasswordButton.snp.makeConstraints { (make) in
        make.right.equalTo(verticalLine.snp.left).offset(-4)
        make.width.equalTo(20)
        make.height.equalTo(10)
        make.centerY.equalTo(passwordField)
    }
    passwordBottomLine.snp.makeConstraints { (make) in
        make.top.equalTo(passwordField.snp.bottom).offset(12)
        make.width.equalTo(335)
        make.height.equalTo(1)
        make.centerX.equalTo(userNameField.snp.centerX)
    }
//    inputStack.translatesAutoresizingMaskIntoConstraints = false
//    let leading = inputStack.leadingAnchor
//      .constraint(equalTo: contentView.leadingAnchor)
//    let trailing = inputStack.trailingAnchor
//      .constraint(equalTo: contentView.trailingAnchor)
//    let top = inputStack.topAnchor
//      .constraint(equalTo: contentView.topAnchor)
//    NSLayoutConstraint.activate(
//      [leading, trailing, top])
  }

  func activateConstraintsSignInButton() {
    signInButton.snp.makeConstraints { (make) in
        make.top.equalTo(passwordBottomLine.snp.bottom).offset(40)
        //make.left.equalTo(20)
        make.width.equalTo(335)
        make.height.equalTo(46)
        make.centerX.equalTo(userNameField.snp.centerX)
    }
    loginStyleExchangeButton.snp.makeConstraints { (make) in
        make.top.equalTo(signInButton.snp.bottom).offset(11)
        make.left.equalTo(signInButton)
        make.width.equalTo(100)
        make.height.equalTo(20)
    }
//    signInButton.translatesAutoresizingMaskIntoConstraints = false
//    let leading = signInButton.leadingAnchor
//      .constraint(equalTo: contentView.leadingAnchor)
//    let trailing = signInButton.trailingAnchor
//      .constraint(equalTo: contentView.trailingAnchor)
//    let top = signInButton.topAnchor
//      .constraint(equalTo: inputStack.bottomAnchor, constant: 20)
//    let bottom = contentView.bottomAnchor
//      .constraint(equalTo: signInButton.bottomAnchor, constant: 20)
//    let height = signInButton.heightAnchor
//      .constraint(equalToConstant: 50)
//    NSLayoutConstraint.activate(
//      [leading, trailing, top, bottom, height])
  }

  func activateConstraintsSignInActivityIndicator() {
//    signInActivityIndicator.translatesAutoresizingMaskIntoConstraints = false
//    let centerX = signInActivityIndicator.centerXAnchor
//      .constraint(equalTo: signInButton.centerXAnchor)
//    let centerY = signInActivityIndicator.centerYAnchor
//      .constraint(equalTo: signInButton.centerYAnchor)
//    NSLayoutConstraint.activate(
//      [centerX, centerY])
  }
}

// MARK: - Dynamic behavior
extension SignInRootView {

  func bindViewModelToViews() {
    bindViewModelToEmailField()
    bindViewModelToPasswordField()
    bindViewModelToSignInButton()
    bindViewModelToSignInActivityIndicator()
  }

  func bindViewModelToEmailField() {
    viewModel
      .emailInputEnabled
      .asDriver(onErrorJustReturn: true)
      .drive(userNameField.rx.isEnabled)
      .disposed(by: disposeBag)
  }

  func bindViewModelToPasswordField() {
    viewModel
      .passwordInputEnabled
      .asDriver(onErrorJustReturn: true)
      .drive(passwordField.rx.isEnabled)
      .disposed(by: disposeBag)
  }

  func bindViewModelToSignInButton() {
    viewModel
      .signInButtonEnabled
      .asDriver(onErrorJustReturn: true)
      .drive(signInButton.rx.isEnabled)
      .disposed(by: disposeBag)
  }

  func bindViewModelToSignInActivityIndicator() {
    viewModel
      .signInActivityIndicatorAnimating
      .asDriver(onErrorJustReturn: false)
      .drive(signInActivityIndicator.rx.isAnimating)
      .disposed(by: disposeBag)
  }
}
